﻿using System;
using UnityEngine;
using System.Collections.Generic;

public class UnitySpritePack :MonoBehaviour
{
	[Serializable]
	public class UnitySpriteGroup
	{
		public Material mat;
		public Sprite[] sprites;
	}

	public UnitySpriteGroup[] groups;

	private Dictionary<string, Sprite> _spriteMap = null;
	private Dictionary<string, Material> _matMap = null;


	void InitMap()
	{
		_spriteMap = _spriteMap ?? new Dictionary<string, Sprite>();
		_matMap = _matMap ?? new Dictionary<string, Material>();
		int count = groups != null ? groups.Length : 0;
		for (int i = 0; i < count; ++i)
		{
			UnitySpriteGroup group = groups[i];
			Material mat =
#if UNITY_EDITOR
				new Material(group.mat);
#else
				group.mat;
#endif
			Sprite[] sprites = group != null ? group.sprites : null;
			int spCount = sprites != null ? sprites.Length : 0;
			for (int j = 0; j < spCount; ++j)
			{
				if (group.mat != null)
				{
					_matMap.Add(sprites[j].name, mat);
				}
				_spriteMap.Add(sprites[j].name, sprites[j]);
			}
		}
	}

	public Sprite GetSprite(string spriteName)
	{
		if (!string.IsNullOrEmpty(spriteName))
		{
			if (_spriteMap == null)
			{
				InitMap();
			}
			Sprite sprite;
			if (_spriteMap.TryGetValue(spriteName, out sprite))
			{
				return sprite;
			}
		}
		return null;
	}

	public Material GetSpriteMat(string spriteName)
	{
		if (!string.IsNullOrEmpty(spriteName))
		{
			if (_matMap == null)
			{
				InitMap();
			}
			Material mat;
			if (_matMap.TryGetValue(spriteName, out mat))
			{
				return mat;
			}
		}
		return null;
	}

}
